
package vashion.azeroth.api.core.interceptor;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.common.encrypt.Md5Encrypt;

@Component
public class ApiInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(ApiInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
    	
//        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
//            ApiResult<Boolean> result = apiCheck(request);
//            if (null != result) {
//            	response.setContentType("application/json");
//                response.getWriter().print(JSON.toJSONString(result));
//                return false;
//            }
//        }
        return true;
    }


    private ApiResult<Boolean> apiCheck(HttpServletRequest request) {
        // 校验非空
    	ApiResult<Boolean> result = validateNullParam(request);
        if (null != result) {
            return result;
        }
        
        // 签名检验
        ApiResult<Boolean> signResult = validateSign(request, "1212");
        
        return signResult;
    }

    private ApiResult<Boolean> validateNullParam(HttpServletRequest request) {
        String sign = request.getParameter("sign");
        if (StringUtils.isBlank(sign)) {
            return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(), "签名" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
        }
        return null;
    }


    @SuppressWarnings("unchecked")
    private ApiResult<Boolean> validateSign(HttpServletRequest request, String md5key) {
        String sign = request.getParameter("sign");
        Map<String, String> sortedMap = new TreeMap<String, String>();
        Map<String, String[]> paramMap = request.getParameterMap();
        
        for (Entry<String, String[]> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            if ("sign".equals(key)) {
                sign = entry.getValue()[0];
                continue;
            }
            sortedMap.put(key, entry.getValue()[0]);
        }
        List<String> valList = new LinkedList<String>();
        for (Entry<String, String> e : sortedMap.entrySet()) {
            valList.add(e.getValue());
        }
        valList.add(md5key);
        String sourceStr = StringUtils.join(valList, "|");
        String mysign = Md5Encrypt.encrypt(sourceStr, "UTF-8");
        
        if (!mysign.equals(sign)) {
            log.error("签名错误，我方原串sourceStr：{},我方加密后sign：{}，对方sign：{}", sourceStr, mysign, sign);
            return ApiResult.newErrorResult(GenericErrorEnum.SIGN_ERROR.getErrorCode(), GenericErrorEnum.SIGN_ERROR.getErrorMessage());
        }
        return null;
    }
}
